<!-- Vue template -->
<template>
  <div class="table_mian">
    <div>
      <PureTableBar title="" style="margin-top: 0">
        <template #buttons>
          <el-button type="primary" :icon="useRenderIcon(AddFill)" @click="DetailsUpdate(undefined)">
            添加
          </el-button>
        </template>
        <template v-slot="{ size, checkList }">
          <pure-table border align-whole="center" showOverflowTooltip table-layout="auto" :loading="loading" size="small"
            :data="dataList" :columns="columns" :checkList="checkList" :pagination="pagination" max-height="220"
            :header-cell-style="{
              background: 'var(--el-table-row-hover-bg-color)',
              color: 'var(--el-text-color-primary)'
            }" @size-change="handleSizeChange" @current-change="handleCurrentChange">
            <template #operation="{ row }">
              <!-- 修改 -->
              <el-button class="reset-margin" link type="primary" :size="size" @click="DetailsUpdate(row)">修改</el-button>
              <!-- 删除 -->
              <el-button class="reset-margin" link type="danger" @click="handleDelete(row)" :size="size">删除</el-button>
            <!-- <el-popconfirm title="是否确认删除?" @confirm="handleDelete(row)">
                <template #reference>
                  <el-button class="reset-margin" link type="danger" :size="size">删除</el-button>
                                      </template>                                                                        </el-popconfirm> -->
            </template>
          </pure-table>
        </template>
      </PureTableBar>
    </div>

    <!-- ---------------------- -->
    <!-- ** SavePanelVisible 添加关键字 -->
    <from-type :SavePanelVisible="SavePanelVisible" :updatePanelVisible="updatePanelVisible" :headers="headers"
      v-if="updatePanelVisible || SavePanelVisible" :setForm="setForm" @ClosePanelVisible="ClosePanelVisible"
      @updateSetForm="updateSetForm" ref="deleteDataList" />
  </div>
</template>
<!-- lang="ts" -->
<script lang="ts" setup>
import { ref, reactive, nextTick, watch, computed } from "vue";
import { usetaskPass, taskTableDetiall } from "@/store/modules/taskPass";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, ElMessageBox } from "element-plus";
import FromType from "./from.vue";
import { cloneDeep } from "@pureadmin/utils";

import AddFill from "@iconify-icons/ri/add-circle-line";
const loading = ref<boolean>(false),
  SavePanelVisible = ref(false), //添加关键字
  updatePanelVisible = ref(false), // 修改关键字
  setForm = ref({}), // 存储需要修改的关键字
  headers = ref([]),
  columns = ref([]); // 关键字头部
const deleteDataList = ref(null);
const cloneDeepLinkData = ref({})
const dataList = ref<any>([]);
const [taskDetiall_, usetaskPass_] = [taskTableDetiall(), usetaskPass()];
// 分页
const pagination = reactive<PaginationProps>({
  total: 0,
  pageSize: 100,
  currentPage: 1,
  background: true
});

const props = defineProps({
  value: {
    type: Object
  },
  lable: {
    type: Object
  },
  updatePanelVisible: {
    type: Boolean
  },
  SavePanelVisible: {
    type: Boolean
  },
  noKeyWordShow: {
    type: Boolean,
  }
});
watch(props, newval => {
  if (newval.value) {
    updateTableHeader(newval.value);
  } else {
    columns.value = [];
  }
  // console.log(newval.lable);

  // 关键字数据列表
  if (newval.lable && newval.lable.length !== 0) {
    console.log(newval.lable.length);
    console.log(dataList.value.length);

    if (newval.lable.length > dataList.value.length) {
      updateTablelist(newval.lable);
    }
  } else {
    dataList.value = [];
    pagination.total = dataList.value.length;
  }
});

// 获取已添加的关键字
watch(
  taskDetiall_,
  newval => {
    if (newval.data.length) {
      newval.data.forEach(item => {
        for (let key in item) {
          if (key.includes('MultipleSelectValue')) {
            item[key] = Array.isArray(item[key]) ? item[key].join('、') : item[key]
          }
        }
      })
    }
    console.log(newval.data);

    dataList.value = newval.data;
    // updateTablelist(dataList.value);
  },
  { deep: true }
);

// 关闭from表单
function ClosePanelVisible() {
  updatePanelVisible.value = false;
  SavePanelVisible.value = false;
}

//更换联动数据类型
function updateSetForm(newData) {
  if (newData.childKeywordId && newData.childSelectContent) {
    //更换选项
    //先保存一份最原始数据在内存中
    if (!cloneDeepLinkData.value[newData.childKeywordId]) {
      cloneDeepLinkData.value[newData.childKeywordId] = cloneDeep(headers.value.submoduleKeywordEntityResultDtos.find(item => item.keywordId == newData.childKeywordId).selectItemDtos)
    }
    let keyArr = newData.childSelectContent.split(',');
    let result = []
    //找到对应的选项
    cloneDeepLinkData.value[newData.childKeywordId].forEach(item => {
      keyArr.forEach(a => {
        if (item.selectItemId == a) {
          result.push(item)
        }
      })
    })
    headers.value.submoduleKeywordEntityResultDtos.forEach(item => {
      if (item.keywordId == newData.childKeywordId) {
        item.selectItemDtos = result
      }
    })
  }
  if (newData.childKeywordId && !newData.childSelectContent) {
    //更换类型
    let keyArr = newData.childKeywordId.split(',');
    headers.value.submoduleKeywordEntityResultDtos.forEach(item => {
      if (keyArr.includes(item.keywordId)) {
        item.keywordType = newData.childKeywordType;
      }
    })
  }
}

// 打开from 表单
function DetailsUpdate(row: any | undefined) {
  if (headers.value.length === 0) {
    ElMessage.warning("请选择操作菜单！");
    return;
  }
  if (typeof row === "object") {
    // 修改
    if (row.multistageChangeKeywordId) {
      let keyArr = row.multistageChangeKeywordId.split(',');
      headers.value.submoduleKeywordEntityResultDtos.forEach(item => {
        if (keyArr.includes(item.keywordId)) {
          item.keywordType = Number(row.multistageChangeKeywordType);
        }
      })
    }
    if (row.multipleSelectValue) {
      const arr = JSON.parse(row.multipleSelectValue)
      arr.forEach(a => {
        row['MultipleSelectValue' + a.key] = a.value.split('、')
      })
    }

    setForm.value = Object.assign({}, row);
    // console.log("s001", setForm.value);
    updatePanelVisible.value = true;
    return;
  }
  SavePanelVisible.value = true;
}

// table 关键字头部
// 优化后
function updateTableHeader(data: any) {
  // console.log(data)
  const rows = data.submoduleKeywordEntityResultDtos.flatMap((r, i) => {
    const Array1 = {
      label: r.keywordName || "",
      prop: r.keywordType === 7 ? `MultipleSelectValue${r.keywordId}` : `value${i + 1}`
    };
    return Array1.label ? [Array1] : [];
  })
    .filter((obj, index, arr) => {
      return arr.findIndex(otherObj => otherObj.label === obj.label) === index;
    });

  columns.value = [
    ...rows,
    {
      label: "操作",
      fixed: "right",
      width: 110,
      slot: "operation"
    }
  ];

  if (data.submoduleKeywordEntityResultDtos.length > 0) {
    nextTick(() => {
      headers.value = data;
    });
  }
}

// table 关键字数据列表
function updateTablelist(data: any) {
  // console.log('我再table');
  console.log(data);

  const obj = data.map(r => {
    return {
      ...r,
      ...{
        planId: usetaskPass_.data.planId,
        taskId: usetaskPass_.data.taskId,
        taskDetailId: 1
      }
    };
  });
  obj.forEach(item => {
    if (item.multipleSelectValue) {
      const arr = JSON.parse(item.multipleSelectValue)
      arr.forEach(a => {
        item['MultipleSelectValue' + a.key] = a.value
      })
    }
  })

  taskDetiall_.data = obj;
  dataList.value = obj;
  pagination.total = dataList.value.length;
}

const newDataList = computed(() => {
  const startIndex = (pagination.currentPage - 1) * pagination.pageSize;
  const endIndex = startIndex + pagination.pageSize;
  return dataList.value.slice(startIndex, endIndex);
});

// 删除关键字
function handleDelete(row: any) {
  ElMessageBox({
    title: '提示', //MessageBox 标题
    closeOnClickModal: false,
    message: '是否确定删除当前项?', //MessageBox 消息正文内容
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    taskDetiall_.DELETE_DATA(row);
  }).catch(() => { })

}

// 监听页面-- 分页显示数量
function handleSizeChange(val: number) {
  // pagination.pageSize = val;
}

// 分页
function handleCurrentChange(val: number) {
  // pagination.currentPage = val;
  // pagination.pageSize - 1;
}
</script>
<style lang="scss" scoped>
.table_mian {
  border: 1px solid #dfdfdd;
  width: 100%;
  margin-top: 20px;
  border-radius: 5px;
}

:deep(.el-pagination) {
  display: none !important;
}
</style>
